<?php

namespace App\Api\Fcjd;

use PhalApi\Api;
use PhalApi\Exception\BadRequestException;

/**
 * 任务编队
 * @author wenfree 20240118
 */
class TaskTeam extends Api
{
    public function getRules()
    {
        return array(
            'getPhoneListTeam' => array(
                'phone_id' => array('name' => 'phone_id', 'require' => true, 'min' => 1, 'desc' => '设备唯一标识'),
            ),
            'set' => array(
                'phone_id' => array('name' => 'phone_id', 'require' => true, 'min' => 1, 'desc' => '设备唯一标识'),
                'number' => array('name' => 'number', 'require' => true, 'desc' => 'number'),
            ),
            'load' => array(
                'phone_id' => array('name' => 'phone_id', 'require' => true, 'min' => 1, 'desc' => '设备唯一标识'),
                'number' => array('name' => 'number', 'require' => true, 'desc' => 'number'),
            ),
            'batchTeam' => array(
                'ids' => array('name' => 'ids', 'type' => 'array', 'require' => true, 'desc' => '需要更新的ID数组'),
                'number' => array('name' => 'number', 'require' => true, 'desc' => 'number'),
            ),
        );
    }


    /**
     * 任务编队-获取
     * @desc 获取指定设备的编队信息
     * @return array team_list 编队记录列表
     */
    public function getPhoneListTeam()
    {
        // 处理跨域
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *,x-token,X-token');

        // 查询编队记录
        $teamList = \PhalApi\DI()->notorm->phone_list_team
            ->where('phone_id', $this->phone_id)
            ->order('number asc')
            ->fetchAll();

        \PhalApi\DI()->response->setMsg('success');
        return $teamList;
    }

    /**
     * 任务编队-设置
     * @desc 一次性获取所有可执行任务
     * @return array tasks 任务列表
     * @return array app_info 应用信息
     * @return array tags 任务标签
     * @return array banners 广告图
     * @return array auto_files 动态文件
     */
    public function set()
    {
        // 处理跨域
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *,x-token,X-token');

        // 获取设备信息
        $device = \PhalApi\DI()->notorm->phone_list
            ->where('id', $this->phone_id)
            ->fetchOne();

        if (!$device) {
            throw new BadRequestException('设备未注册');
        }

        $update = \PhalApi\DI()->notorm->phone_list_team
            ->where( array('phone_id' => $this->phone_id, 'number' => $this->number ) )
            ->update(array(
                'update_time' => date('Y-m-d H:i:s', time()),
                'phone_id' => $this->phone_id,
                'number' => $this->number,
                'mobile' => $device['mobile'],
                'task' => $device['task'],
                'task2' => $device['task2'],
            ));

        if( !$update ){
            $update = \PhalApi\DI()->notorm->phone_list_team
            ->insert(array(
                'create_time' => date('Y-m-d H:i:s', time()),
                'phone_id' => $this->phone_id,
                'number' => $this->number,
                'mobile' => $device['mobile'],
                'task' => $device['task'],
                'task2' => $device['task2'],
            ));
        }
     
        \PhalApi\DI()->response->setMsg('success');
        return '保存设置';
    }

    
    /**
     * 任务编队-加载（逆向还原）
     * @desc 将phone_list_team中指定记录的task/task2还原到phone_list
     * @return string 操作结果描述
     */
    public function load()
    {
        // 处理跨域
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *,x-token,X-token');

        // 1. 验证设备存在
        $device = \PhalApi\DI()->notorm->phone_list
            ->where('id', $this->phone_id)
            ->fetchOne();
        if (!$device) {
            throw new BadRequestException('设备未注册');
        }

        // 2. 获取phone_list_team中指定number的记录
        $teamRecord = \PhalApi\DI()->notorm->phone_list_team
            ->where(array(
                'phone_id' => $this->phone_id,
                'number' => $this->number
            ))
            ->fetchOne();
        if (!$teamRecord) {
            throw new BadRequestException('指定编队记录不存在');
        }

        // 3. 还原task和task2到phone_list
        $updateResult = \PhalApi\DI()->notorm->phone_list
            ->where('id', $this->phone_id)
            ->update(array(
                'task' => $teamRecord['task'],
                'task2' => $teamRecord['task2'],
                'update_time' => date('Y-m-d H:i:s', time())
            ));

        if (!$updateResult) {
            throw new BadRequestException('还原失败，请重试');
        }

        \PhalApi\DI()->response->setMsg('success');
        return array('msg'=> '成功加载', 'task'=> $teamRecord['task'], 'task2'=> $teamRecord['task2']);
    }


    /**
     * 批量更新预设设置
     * 
     * @desc 根据传入的ids数组和tasks数组追加任务设置
     * @return array
     */
    public function batchTeam()
    {
        $ids = $this->ids;
        $number = $this->number;

        // 获取所有指定ID的记录当前的task值
        $records = \PhalApi\DI()->notorm->phone_list
            ->select('*')
            ->where(array('id' => $ids))
            ->fetchAll();

        $updateCount = 0;
        $updates = array();

        // return $records;
        foreach ($records as $record) {
            // 获取现有的任务数组
            
            //按 mobile 和 number 取出 team_list 表中指定的任务
            $teamList = \PhalApi\DI()->notorm->phone_list_team
                ->where(array(
                    'phone_id' => $record['id'],
                    'number' => $number
                ))
                ->fetchOne();

            if($teamList){
                $saveInfo = array();
                if($teamList['task']){
                    $saveInfo['task'] = $teamList['task'];
                }
                if($teamList['task2']){
                    $saveInfo['task2'] = $teamList['task2'];
                }
                $updates[]= \PhalApi\DI()->notorm->phone_list
                    ->where('id', $record['id'])
                    ->update($saveInfo);
            }
            
            if ($teamList) {
                $updateCount++;
            }
        }

        \PhalApi\DI()->response->setMsg('设置成功');
        return array(
            'updated_ids' => $ids,
            'updates' => $updates,
            'updateCount' => $updateCount,
        );
    }
}
